﻿using doufu.Common;
using doufu.Common.Extensen;
using doufu.Model;
using System;
using System.Net;
using System.Web.Mvc;

namespace doufu.WebUI.Controllers
{
    public class UserController : BaseController
    {
        //
        // GET: /users/

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOnOpen(users users)
        {

            var dbusers = Services.User.GetOpenUser(users.openId, users.openType);
            if (dbusers != null)
            {
                Services.User.SignIn(dbusers.user_id.ToString(), users.RememberMe);
            }
            else
            {
                dbusers = Services.User.Details(users.openId);
                if (dbusers != null)
                {
                    dbusers.accessToken = users.accessToken;
                    Services.User.Save(dbusers);
                }
                else
                {
                    string url = string.Format("https://graph.qq.com/user/get_user_info?access_token={1}&oauth_consumer_key={0}&openid={2}", users.accessToken, users.openId, Config.QQApiKey);
                    var wc = new WebClient { Encoding = System.Text.Encoding.UTF8 };
                    var jsonstr = wc.DownloadString(url);
                    var qquser = jsonstr.FromJson<QQRetInfo>();
                    if (qquser.ret > 0)
                    {
                        return Content(string.Format("ret:{0},msg:{1}", qquser.ret, qquser.msg));
                    }
                    dbusers = new users
                    {
                        user_id = 0,
                        user_name = qquser.nickname,
                        fullname = qquser.nickname,
                        openId = users.openId,
                        accessToken = users.accessToken,
                        gender = qquser.gender == "男" ? 0 : 1,

                    };
                    Services.User.Save(dbusers);
                }
                Services.User.SignIn(dbusers.user_id.ToString(), dbusers.RememberMe);
            }
            return Content("1");
        }

        [HttpPost]
        public ActionResult LogOn(users users, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                users = Services.User.GetByNameAndPassword(users.user_name, users.password);

                if (users != null)
                {
                    Services.User.SignIn(users.user_id.ToString(), users.RememberMe);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "提供的用户名或密码不正确。");
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(users);
        }
        public ActionResult LogOff()
        {
            Services.User.SignOut();
            return View();
        }

        public ActionResult NoRight()
        {
            Title = "无权访问资源";
            return View();
        }
        [UserAuthorize]
        public ActionResult UserList(int? page)
        {
            Title = "用户列表";
            return View(Services.User.Pager(page ?? 1));
        }
        [UserAuthorize]
        public ActionResult Edit(int? id)
        {
            var entity = id.HasValue ? Services.User.Details(id.Value) : new users();
            return View(entity);
        }

        [UserAuthorize]
        [HttpPost]
        public ActionResult Edit(users entity)
        {
            Services.User.Save(entity);
            return RedirectToAction("UserList");
        }

        #region Permission
        [UserAuthorize]
        public ActionResult PermissionList(int? page)
        {
            Title = "权限列表";
            return View(Services.User.PermissionPager(page ?? 1));
        }

        [UserAuthorize]
        public ActionResult AddPermission(int? id)
        {
            var entity = id.HasValue ? Services.User.PermissionDetails(id.Value) : new permission();
            return View(entity);
        }

        [UserAuthorize]
        [HttpPost]
        public ActionResult AddPermission(permission entity)
        {
            Services.User.PermissionSave(entity, this);
            return RedirectToAction("PermissionList");
        }
        #endregion

        #region UserPermission
        [UserAuthorize]
        public ActionResult UserPermission(int id)
        {
            var ret = Services.User.UserPermission(id);
            return View(ret);
        }
        [HttpPost]
        [UserAuthorize]
        public ActionResult SaveUserPermission(int userId, int permissionId)
        {
            try
            {
                Services.User.SaveUserPermission(userId, permissionId, this);
                return Content("1");
            }
            catch (Exception e)
            {
                return Content(e.ToString());
            }
        }
        #endregion
    }
}
